package com.leo.config;

import com.leo.util.Base64Util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName: MyPropertyPlaceholder
 * @Description: 配置文件解析
 * @Author: leo825
 * @Date: 2020-05-16 23:00
 * @Version: 1.0
 */
public class MyPropertyPlaceholder extends PreferencesPlaceholderConfigurer {
    //定义一个属性的map对象
    private final static Map<String, String> propertyMap = new HashMap();
    /**
     * 这里要特别留意下，可以使用这种方式实现配置文件加解密，最常见的是对数据库的配置的加解密
     *
     * @param beanFactoryToProcess
     * @param props
     * @throws BeansException
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        for (Object keyString : props.keySet()) {
            String key = keyString.toString();
            String value = props.getProperty(key);
            //此处是做了配置文件的解密处理，以防止配置文件明文引起安全问题
            if("datesource.username".equals(key) || "datesource.password".equals(key)){
                try {
                    value = Base64Util.decodeDate(value);
                } catch (Exception e) {
                    e.printStackTrace();
                    value = "";
                }
            }
            propertyMap.put(key, value);
        }
    }
    //自定义一个方法，即根据key拿属性值,方便java代码中取属性值
    public static String getProperty(String name) {
        return propertyMap.get(name);
    }
}
